package com.spring.sunflower.conversation

import android.content.Intent
import android.widget.RelativeLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.lxj.xpopup.XPopup
import com.makeramen.roundedimageview.RoundedImageView
import com.spring.sunflower.R
import com.spring.sunflower.anchor.PersonalDetailActivity
import com.spring.sunflower.base.BaseActivity
import com.spring.sunflower.bean.LabelBean
import com.spring.sunflower.common.ReportActivity
import com.spring.sunflower.constant.Constant
import com.spring.sunflower.event.PinnedConversationEvent
import com.spring.sunflower.widget.ToggleView
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager
import jp.wasabeef.glide.transformations.CropCircleTransformation
import org.greenrobot.eventbus.EventBus
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by Kevin on 2021/8/18<br/>
 *
 * Describe:<br/>
 */
class ChatCommentActivity : BaseActivity<ChatCommentPresenter>(),
    ConversationContract.ChatCommentView {
    private var ivAvatar: RoundedImageView? = null
    private var tvNickname: TextView? = null
    private var tvFollow: TextView? = null
    private var toggleTop: ToggleView? = null
    private var toggleBlack: ToggleView? = null
    private var rlReport: RelativeLayout? = null
    private var rlAvatar: RelativeLayout? = null
    private var mHasBlacked = false
    private var mHasFollowed = false
    private var isPinned = false//默认不置顶
    private var mTopUserIDData = LinkedList<String>()
    private val mLabelNameList: MutableList<String> = ArrayList()
    private var mLabelData: List<LabelBean.DatasBean?>? = null
    private var otherUserId = ""
    override fun initView() {
        val intent = intent
        val otherAvatar = intent.getStringExtra("otherAvatar")
        val otherNickname = intent.getStringExtra("otherNickname")
        otherUserId = getField(Constant.KEY_USERID_CHATTER, "")
        val userId = intent.getStringExtra("userId")
        tvTitle.text = "聊天设置"
        ivAvatar = findViewById(R.id.ivAvatar)
        tvNickname = findViewById(R.id.tvNickname)
        tvFollow = findViewById(R.id.tvFollow)
        toggleTop = findViewById(R.id.toggle_top)
        toggleBlack = findViewById(R.id.toggle_black)
        rlReport = findViewById(R.id.rlReport)
        rlAvatar = findViewById(R.id.rlAvatar)

        mTopUserIDData.clear()
        val conversationID = "c2c_${otherUserId}"
        val pinnedListString = getField(Constant.C2C_PINNED, "")
        val result = pinnedListString.removeSurrounding("[", "]")
            .replace(" ", "")
            .split(",")
            .map {
                mTopUserIDData.add(it)
                it.toString()
            }

        isPinned = result.contains(otherUserId)//包含就是置顶true不包含就是false
        printD("pinnedList=${pinnedListString},top=" + isPinned + ",otherUserId=" + otherUserId)
        toggleTop?.setChecked(isPinned)//
        toggleTop?.setDelayChecked(true)
        toggleTop?.setOnClickListener {
            if (isFastClick) {
                showToast("请勿频繁操作")
                return@setOnClickListener
            }
            V2TIMManager.getConversationManager()
                .pinConversation(conversationID, !isPinned, object : V2TIMCallback {
                    override fun onSuccess() {
                        toggleTop?.setChecked(!isPinned)
                        val pinnedConversationEvent = PinnedConversationEvent()
                        pinnedConversationEvent.userID = otherUserId
                        pinnedConversationEvent.isPinned = !isPinned
                        EventBus.getDefault().post(pinnedConversationEvent)
                        printD("!top=" + !isPinned)
                        if (isPinned) {//
                            mTopUserIDData.remove(otherUserId!!)
                        } else {
                            mTopUserIDData.add(otherUserId!!)
                        }
                        isPinned = !isPinned
                        printD("mTopUserIDData" + mTopUserIDData.toString())
                        saveField(Constant.C2C_PINNED, mTopUserIDData.toString())
                    }

                    override fun onError(code: Int, desc: String?) {

                    }

                })
        }
        Glide.with(this)
            .load(otherAvatar)
            .placeholder(R.drawable.ic_placeholder)
            .error(R.drawable.ic_placeholder)
            .apply(RequestOptions.bitmapTransform(CropCircleTransformation()))
            .into(ivAvatar!!)
        tvNickname?.text = otherNickname
        rlAvatar?.setOnClickListener {
            val intent = Intent(this, PersonalDetailActivity::class.java)
            intent.putExtra(Constant.KEY_TARGET_ID, otherUserId!!)
            startActivity(intent)
        }
        toggleBlack?.setDelayChecked(true)
        toggleBlack?.setOnClickListener {
            if (isFastClick) {
                showToast("请勿频繁操作")
                return@setOnClickListener
            }
            if (mHasBlacked) {
                mPresenter.blackRemove(otherUserId!!)
            } else {
                mPresenter.blackAdd(otherUserId!!)
            }
        }
        rlReport?.setOnClickListener {
            if (isFastClick) return@setOnClickListener
            if (mLabelData == null) {
                showToast("暂无可举报类型，稍后重试")
                return@setOnClickListener
            }
            mLabelData?.let {
                showReportBottomDialog(it)
            }
        }
        tvFollow?.setOnClickListener {
            if (isFastClick) return@setOnClickListener
            mPresenter.setFollowed(
                otherUserId!!,
                if (mHasFollowed) "0" else "1"
            )
        }
        mPresenter.getHasBlacked(otherUserId!!, userId!!)
        mPresenter.getHasFollowed(otherUserId!!)
        mPresenter.getReportType()
    }

    override fun getLayoutID(): Int = R.layout.activity_chat_comment

    override fun setPresenter(): ChatCommentPresenter = ChatCommentPresenter(this)

    override fun onResume() {
        super.onResume()

    }

    override fun showReportType(data: List<LabelBean.DatasBean?>?) {
        mLabelData = data!!
    }

    private fun showReportBottomDialog(data: List<LabelBean.DatasBean?>?) {
        mLabelNameList.clear()
        for (d in data!!) {
            val name = d!!.name
            mLabelNameList.add(name)
        }
        val stringArr: Array<String> = mLabelNameList.toTypedArray<String>()
        XPopup.Builder(this)
            .hasShadowBg(true)
            .asBottomList(
                null, stringArr
            ) { position, text ->
                val intent = Intent(this, ReportActivity::class.java)
                intent.putExtra(Constant.KEY_REPORT_TYPE, data[position])
                intent.putExtra("reportName", text)
                intent.putExtra("otherID", otherUserId)
                startActivity(intent)
            }
            .show()
    }

    override fun hasBlacked(hasBlacked: Boolean) {
        mHasBlacked = hasBlacked
        toggleBlack?.setChecked(hasBlacked)
    }

    override fun blackAddSuccess() {
        mHasBlacked = true
        toggleBlack?.setChecked(true)
    }

    override fun blackAddFailed() {
        mHasBlacked = false
        toggleBlack?.setChecked(false)
    }

    override fun blackRemoveSuccess() {
        mHasBlacked = false
        toggleBlack?.setChecked(false)
    }

    override fun blackRemoveFailed() {
        mHasBlacked = true
        toggleBlack?.setChecked(true)
    }

    override fun hasFollowed(hasFollowed: Boolean) {
        mHasFollowed = hasFollowed
    }

    override fun setFollowedSuccess() {
        mHasFollowed = !mHasFollowed
        if (mHasFollowed) {
            tvFollow?.text = "取消关注"
            tvFollow?.setBackgroundResource(R.drawable.ic_btn_bg_click_disable)
        } else {
            tvFollow?.text = "关注"
            tvFollow?.setBackgroundResource(R.drawable.ic_btn_bg_click_enable)
        }
    }

    override fun setFollowedFailed() {
    }

    override fun onPause() {
        super.onPause()
        printD("onPause")
    }

    override fun onStop() {
        super.onStop()
        printD("onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        printD("onDetroy")
    }
}